using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;
using ResultManagement;
using System.Collections;
using System.Web.UI.DataVisualization.Charting;
using System.Data.SqlClient;
using System.Configuration;
using LuceneManager;

namespace KnowFirstWebApplication
{
    public partial class Reports : basePageSessionExpire
    {
        public int daysback = Int32.Parse(ConfigurationManager.AppSettings["DaysBack"]);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DisplayDocumentTypeList();
                //Session[USERNAME] = "roeyaus";
                 User User = GetCurrentUser();
                PopulateDateCombos();
                DisplayUserCategoryNames(User);
                if (User.Categories.Count > 0)
                {
                    ViewState[UIHelper.CATEGORY] = User.Categories[0].Name;
                    lbCategories.SelectedIndex = 0;
                    DisplaySelectedCategoryQueries(lbCategories.SelectedValue);
                    lbCategories.SelectedIndex = 0;
                       //PopulateDateCBs(Document.GetDocumentMinDate(results), Document.GetDocumentMaxDate(results));
                    PopulateDateCBs(DateTime.Now.Subtract(new TimeSpan(168, 0, 0)), DateTime.Now.Add(new TimeSpan(24, 0, 0)));
                }
            }
        }

        public void PopulateDateCBs(DateTime FromDate, DateTime ToDate)
        {
            cbFromYear.Text = FromDate.Year.ToString();
            cbFromMonth.Text = FromDate.Month.ToString();
            cbFromDay.Text = FromDate.Day.ToString();
            cbToYear.Text = ToDate.Year.ToString();
            cbToMonth.Text = ToDate.Month.ToString();
            cbToDay.Text = ToDate.Day.ToString();
        }
        public DateTime GetFromDate()
        {
            return new DateTime(Int32.Parse(cbFromYear.Text),
                Int32.Parse(cbFromMonth.Text), Int32.Parse(cbFromDay.Text));
        }
        public DateTime GetToDate()
        {
            return new DateTime(Int32.Parse(cbToYear.Text),
                Int32.Parse(cbToMonth.Text), Int32.Parse(cbToDay.Text));
        }
        User GetCurrentUser()
        {
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer();
            User User = dal.GetUserByUserName(Session[UIHelper.USERNAME] as string);
            return User;
        }
        Category GetCurrentCategory()
        {
            User User = GetCurrentUser();
            return User.GetCategoryByName(ViewState[UIHelper.CATEGORY] as string);
        }
        public void DisplayDocumentTypeList()
        {
            cblDocumentTypes.DataSource = Document.GetDocumentTypesNameList();
            cblDocumentTypes.DataBind();
            foreach (ListItem li in cblDocumentTypes.Items)
                li.Selected = true;
        }
        private void DisplayUserCategoryNames(User User)
        {
            lbCategories.Items.Clear();
            lbCategories.DataSource = User.Categories;
            lbCategories.DataBind();
        }
        private List<Document.Type> GetSelectedDocTypes()
        {
            List<Document.Type> docTypes = new List<Document.Type>();
            for (int i = 0; i < cblDocumentTypes.Items.Count; i++)
            {
                if (cblDocumentTypes.Items[i].Selected)
                    docTypes.Add((Document.Type)i);
            }
            return docTypes;
        }

        public void PopulateDateCombos()
        {
            cbFromDay.DataSource = UIHelper.GetDaysInMonth();
            cbFromDay.DataBind();
            cbFromMonth.DataSource = UIHelper.GetMonthesInYear();
            cbFromMonth.DataBind();
            cbFromYear.DataSource = UIHelper.GetYearsFrom1990To2020();
            cbFromYear.DataBind();
            cbToDay.DataSource = UIHelper.GetDaysInMonth();
            cbToDay.DataBind();
            cbToMonth.DataSource = UIHelper.GetMonthesInYear();
            cbToMonth.DataBind();
            cbToYear.DataSource = UIHelper.GetYearsFrom1990To2020();
            cbToYear.DataBind();

        }

        protected void btnAddQuery_Click(object sender, EventArgs e)
        {
            if (!lbSelectedQueries.Items.Contains(new ListItem(lbQueries.SelectedValue)))
                lbSelectedQueries.Items.Add(new ListItem(lbQueries.SelectedValue));
        }
        protected void btnRemoveQuery_Click(object sender, EventArgs e)
        {
            lbSelectedQueries.Items.Remove(new ListItem(lbSelectedQueries.SelectedValue));
        }

        protected void lbCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState[UIHelper.CATEGORY] = lbCategories.SelectedValue;
            DisplaySelectedCategoryQueries(lbCategories.SelectedValue);
        }

        public void DisplaySelectedCategoryQueries(string categoryName)
        {
            Category cat = GetCurrentCategory();
            lbQueries.DataSource = cat.Queries;
            lbQueries.DataBind();
            lbSelectedQueries.DataSource = cat.Queries;
            lbSelectedQueries.DataBind();
        }

        protected void btnLoadCategory_Click(object sender, EventArgs e)
        {
            User User = GetCurrentUser();
            //ResultManager rm = new ResultManager("", HttpContext.Current.Server.MapPath("~/App_Data/HebrewPrefixes.txt"));
            //List<Document> results = Document.SortDocumentsByPriorityDate(rm.GetUserCategoryResults(User.UserName, GetCurrentCategory(), true));
            InitMentionsByDate();
            LuceneReader reader = new LuceneReader(UIHelper.LoadIndexNodes().ToArray());
            foreach (ListItem li in lbSelectedQueries.Items)
            {
                if (!li.Value.Equals(string.Empty))
                    AddSeriesToMentionsByDate(li.Value, reader);
            }

        }

        void InitMentionsByDate()
        {
            chartMentionsByDate.Series.Clear();
        }
        void AddSeriesToMentionsByDate(string query, LuceneReader reader)
        {
            Series OriginalSeries = new Series(query);
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer();
            int temp;
            List<Document> docs = reader.GetDocumentsMatchingQuery(query, -1 , -1,
                out temp);
            var sorted = from d in docs
                         where
                         d.dateTime <= GetToDate()
                         &&
                         d.dateTime >= GetFromDate()
                         
                         orderby
                             d.DateTime ascending
                         select d;
            docs = new List<Document>(sorted);
            chartMentionsByDate.Series.Add(query);
            chartMentionsByDate.Series[query].Points.DataBindXY(docs, "dateTime", docs, "Id");
            string formula = "Count, X:First";

            chartMentionsByDate.DataManipulator.Group(formula, 1, IntervalType.Days, query);

            chartMentionsByDate.ChartAreas["ChartArea1"].AxisX.LabelStyle.Interval = 1;
            chartMentionsByDate.ChartAreas["ChartArea1"].AxisX.MajorGrid.Interval = 1;
            chartMentionsByDate.ChartAreas["ChartArea1"].AxisX.MajorTickMark.Interval = 1;
            chartMentionsByDate.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = true;

            chartMentionsByDate.Legends.Add(new Legend(query));



        }






    }

   
}
